package com.ikun.aimian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ikun.aimian.common.BaseResponse;
import com.ikun.aimian.common.DeleteRequest;
import com.ikun.aimian.common.ErrorCode;
import com.ikun.aimian.common.ResultUtils;
import com.ikun.aimian.exception.BusinessException;
import com.ikun.aimian.exception.ThrowUtils;
import com.ikun.aimian.model.dto.interview.InterviewPostAddRequest;
import com.ikun.aimian.model.dto.interview.InterviewPostDeleteRequest;
import com.ikun.aimian.model.dto.interview.InterviewPostEditRequest;
import com.ikun.aimian.model.dto.interview.InterviewPostQueryRequest;
import com.ikun.aimian.model.entity.InterviewPost;
import com.ikun.aimian.model.entity.User;
import com.ikun.aimian.model.entity.UserFavorite;
import com.ikun.aimian.model.vo.InterviewPostVO;
import com.ikun.aimian.service.InterviewPostService;
import com.ikun.aimian.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/interview_post")
@Slf4j
public class InterviewPostController {

    @Resource
    private InterviewPostService interviewPostService;

    @Resource
    private UserService userService;

    /**
     * 新增帖子（用户需登录）
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody InterviewPostAddRequest addRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(addRequest == null, ErrorCode.PARAMS_ERROR);
        InterviewPost post = new InterviewPost();
        post.setTitle(addRequest.getTitle());
        post.setContent(addRequest.getContent());
        post.setDifficulty(addRequest.getDifficulty());

        // 从 UserService 获取当前登录用户
        User user = userService.getLoginUser(request);
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");
        post.setUserId(user.getId());

        interviewPostService.validPost(post, true);
        boolean result = interviewPostService.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "帖子发布失败");
        return ResultUtils.success(post.getId());
    }

    /**
     * 编辑帖子（只有管理员或帖子作者可以编辑）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody InterviewPostEditRequest editRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(editRequest == null || editRequest.getId() == null || editRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        InterviewPost post = new InterviewPost();
        post.setId(editRequest.getId());
        post.setTitle(editRequest.getTitle());
        post.setContent(editRequest.getContent());

        // 获取当前登录用户
        User user = userService.getLoginUser(request);
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");

        InterviewPost oldPost = interviewPostService.getById(editRequest.getId());
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR, "帖子不存在");

        boolean isAdmin = userService.isAdmin(user);
        boolean isOwner = oldPost.getUserId() != null && oldPost.getUserId().equals(user.getId());
        ThrowUtils.throwIf(!isAdmin && !isOwner, ErrorCode.NO_AUTH_ERROR, "无权限编辑该帖子");

        interviewPostService.validPost(post, false);
        boolean result = interviewPostService.updateById(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "帖子编辑失败");
        return ResultUtils.success(true);
    }

    /**
     * 根据帖子ID获取帖子封装（帖子详情）
     */
    @GetMapping("/get/vo")
    public BaseResponse<InterviewPostVO> getPostVOById(@RequestParam Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        InterviewPost post = interviewPostService.getById(id);
        ThrowUtils.throwIf(post == null, ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        InterviewPostVO vo = interviewPostService.getPostVO(post, request);
        return ResultUtils.success(vo);
    }

    /**
     * 分页查询帖子列表（所有用户可见）
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<InterviewPostVO>> listPostByPage(@RequestBody InterviewPostQueryRequest queryRequest,
                                                              HttpServletRequest request) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        Page<InterviewPost> postPage = interviewPostService.page(new Page<>(current, size),
                interviewPostService.getQueryWrapper(queryRequest));
        Page<InterviewPostVO> voPage = interviewPostService.getPostVOPage(postPage, request);
        return ResultUtils.success(voPage);
    }

    /**
     * 分页查询当前登录用户的帖子列表（用户自己可见）
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<InterviewPostVO>> listMyPostByPage(@RequestBody InterviewPostQueryRequest queryRequest,
                                                                HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        // 强制过滤当前用户的帖子
        QueryWrapper<InterviewPost> queryWrapper = interviewPostService.getQueryWrapper(queryRequest);
        queryWrapper.eq("userId", user.getId());
        Page<InterviewPost> postPage = interviewPostService.page(new Page<>(current, size), queryWrapper);
        Page<InterviewPostVO> voPage = interviewPostService.getPostVOPage(postPage, request);
        return ResultUtils.success(voPage);
    }

    /**
     * 删除帖子（只有管理员或帖子作者可删除）
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody InterviewPostDeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        User user = userService.getLoginUser(request);
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");

        Long id = deleteRequest.getId();

        boolean isAdmin = userService.isAdmin(request);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限删除");
        }

        // 使用 UpdateWrapper 来指定更新字段和 WHERE 条件
        UpdateWrapper<InterviewPost> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .eq("isDelete", 0)
                .set("isDelete", 1);

        boolean result = interviewPostService.update(null, updateWrapper);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(true);
    }

}
